var chess = document.getElementById('chess');
var context = chess.getContext('2d');
var zis = []; // 所有的子
var me = true; //黑子或白子
var over = false;

(function (w,a,b,undefined) {//赢法初始化
	var wins = []; //赢法
	for (var i = 0 ;i<a;i++) {
		wins[i] = [];
		for(var j =0;j<b;j++){
			wins[i][j]=[];
		}
	}

	var count = 0 ;
	for(var i =0;i<a;i++){//横向赢法
		for(var j=0;j<b-4;j++){
			for(var k=0;k<5;k++){
				wins[i][j+k][count]=true;
			}
			count++;
		}
	}
	for(var i =0;i<a;i++){//列向赢法
		for(var j=0;j<b-4;j++){
			for(var k=0;k<5;k++){
				wins[j+k][i][count]=true;
			}
			count++;
		}
	}
	for(var i =0;i<a-4;i++){//斜线赢法
		for(var j=0;j<b-4;j++){
			for(var k=0;k<5;k++){
				wins[i+k][j+k][count]=true;
			}
			count++;
		}
	}
	for(var i =0;i<a-4;i++){//斜线赢法
		for(var j=14;j>3;j--){
			for(var k=0;k<5;k++){
				wins[i+k][j-k][count]=true;
			}
			count++;
		}
	}
	w.myWin = [];
	w.comWin = [];
	for(var i =0;i<count;i++){
		w.myWin[i]=w.comWin[i]=0;
	}
	w.wins = wins;
	w.count = count;
})(window,15,15);



for(var i =0;i<15;i++){
	zis[i] = [];
}

for(var i =0;i<15;i++){

	var x=15+i*30,y1=15,y2=435;
	context.moveTo(x,y1);
	context.lineTo(x,y2);
	context.stroke();
	context.moveTo(y1,x);
	context.lineTo(y2,x);

	context.stroke();
}

function oneStep(i,j,me) {
	var x = 15+i*30,y = 15+j*30;
	context.beginPath();
	context.arc(x,y,13,0,2*Math.PI);
	context.closePath();
	var gdt = context.createRadialGradient(x,y,10,x,y,3);
	if(me){
		gdt.addColorStop(0,"#333");
		gdt.addColorStop(1,"#ccc");
	}else{
		gdt.addColorStop(0,"#aaa");
		gdt.addColorStop(1,"#eee");
	}
	
	context.fillStyle=gdt;
	context.fill();
}


chess.onclick = function (e) {
	if(over)return;
	var x = Math.floor(e.layerX/30);
	var y = Math.floor(e.layerY/30);
	if(!zis[x][y]){
		oneStep(x,y,me);
		zis[x][y] = me?1:2;
		me = !me;
		for(var k =0;k<count;k++){
			if(wins[y][x][k]){
				myWin[k]++;
				comWin[k]=-1;
				if(myWin[k]==5){
					alert('你赢了');
					over = true;
				}
			}
		}
	}
	
}


